<?php
namespace app\applet\controller;

use Stbz\Api\SupplyClient;
use think\Config;
use think\Db;
use think\Validate;

class SupplyChain
{
    private $appKey   = 'A855F0BA1EBCD119BEFBDE6EC07ECE65';
    private $appSecret = '68B892679EB78F9FB45ED3D62DE838B7';

    public function __construct()
    {
        vendor("JuHe.autoload");
        $this->client = new SupplyClient( $this->appKey, $this->appSecret);
        $this->supply = new \app\applet\model\SupplyChain();
    }
    #zlc-获取用户的金币和积分信息
    public function getUserMoney()
    {
        $data = $this->supply->getUserMoney();
        returnJson(200,"success",$data);
    }
    #供应链提交下单
    public function order()
    {
        $param =[
	'address'=>[
		'consignee' => '小胜',
		'phone' => '13000000000',
		'province' => '北京市',
		'city' => '北京市',
		'area' => '丰台区',
		'street' => '卢沟桥街道',
		'description' => '和谐银座商场',
	],

	'spu' => [
		[
			'sku'=>15570,//skuId
			'number'=>1,
		],
	],
	'orderSn'=>'thirdsn20200617160900001',//

];
//        $param = [];
        $method = 'POST';//请求方法
        $action = '/v2/order';//请求资源名
        $response = $this->client->getApiResponse($method,$action,$param);
        dump($response);die;
        $response = json_decode($response,true);
    }
    #zlc-地址定位
    public function freight()
    {
        $param = input();
        $validate = new Validate([
            ['lat', 'require', '纬度不能为空'],
            ['lng', 'require', '经度不能为空'],
            ['id', 'require', '商品规格ID不能为空'],
        ]);
        if(!$validate->check($param))
        {
            returnJson(-2003,$validate->getError());
        }
        $lat = $param['lat'];
        $lng = $param['lng'];
        $ak = "5ffgk3sQOYSIDrWmL1DFtE7Wea7BLtRG";
        $url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=".$ak."&output=json&coordtype=wgs84ll&location=".$lat.','.$lng;
        $address_data = curlHttp($url);
        $address_data = $address_data['result']['addressComponent'];
        $province = $address_data['province'];
        if($province === "")
        {
            returnJson(-2004,"经纬度异常");
        }
        $city = $address_data['city'];
        $area = $address_data['district'];
        $street = empty($address_data['street']) ? $address_data['district'] : $address_data['street'];
        $param1 =[
            'address'=>[
                'consignee' => '默认',
                'phone' => '13000000000',
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'description' => $street,
            ],
            'spu' => [
                [
                    'sku'=>intval($param['id']),
                    'number'=>1,
                ],
            ],
        ];
        $method = 'POST';//请求方法
        $action = '/v2/order/beforeCheck';//请求资源名
        $response = $this->client->getApiResponse($method,$action,$param1);
        $response = json_decode($response,true);
        if($response['code'] === 10002)
        {
            returnJson(-2004,"该商品已下架");
        }
        if($response['code'] === -1)
        {
            returnJson(-2004,"商品规格ID异常");
        }
        $response = $response['data'][0];
        $return_data['freight'] = $response['freight'] / 100;
        $return_data['sku_id'] = $response['skus'][0];
        returnJson(200,"success",$return_data);

    }

    #zlc-供应链Api商品详情
    public function goodsDetail()
    {
        $param = input();
        $validate = new Validate([
            ['id', 'require', '商品ID不能为空'],
        ]);
        if(!$validate->check($param))
        {
            returnJson(-2003,$validate->getError());
        }
        $method = 'GET';//请求方法
        $action = '/v2/Goods/Detail';//请求资源名
        $response = $this->client->getApiResponse($method,$action,$param);
        $response = json_decode($response,true);
        if($response['code'] !== 1)
        {
            returnJson(-2004,"商品ID异常");
        }
        $response = $response['data'];

        #处理价格数据
        ##爆品商城
        $response['market_price'] = sprintf("%.2f",$response['market_price'] / 100);
        $response['hot_agreement_price'] = sprintf("%.2f",$response['agreement_price'] * getReturnPop($response['id'],2) / 100);
        $response['hot_back_gold_coin'] = sprintf("%.1f",$response['agreement_price'] * getReturnPop($response['id'],2) * 2 / 100);
        ##返利商城数据
        $response['return_agreement_price'] = sprintf("%.2f",$response['agreement_price'] * getReturnPop($response['id'],1) / 100);
        $response['return_back_buy_integral'] = sprintf("%.1f",$response['agreement_price'] * 0.2 / 100);
        $response['return_back_one_integral'] = sprintf("%.1f",$response['agreement_price'] * 0.05 / 100);
        $response['return_back_two_integral'] = sprintf("%.1f",$response['agreement_price'] * 0.05 / 100);
        $response['return_back_gold_coin'] = sprintf("%.1f",$response['agreement_price'] * Config::get("gold_coin_config") / 100);

        #处理option中的价格数据
        foreach ($response['specs']['options'] as $k=>$v)
        {
            #爆品商城处理数据结构
            $response['specs']['options'][$k]['market_price'] = sprintf("%.2f",$v['market_price'] / 100);
            $response['specs']['options'][$k]['hot_agreement_price'] = sprintf("%.2f",$v['agreement_price'] * getReturnPop($v['goods_id'],2) / 100);
            $response['specs']['options'][$k]['hot_back_gold_coin'] = sprintf("%.1f",$v['agreement_price'] * getReturnPop($v['goods_id'],2) * 2 / 100);

            #返利商城处理数据结构
            $response['specs']['options'][$k]['return_agreement_price'] = sprintf("%.2f",$v['agreement_price'] * getReturnPop($v['goods_id'],1) / 100);
            $response['specs']['options'][$k]['return_back_buy_integral'] = sprintf("%.1f",$v['agreement_price'] * 0.2 / 100);
            $response['specs']['options'][$k]['return_back_one_integral'] = sprintf("%.1f",$v['agreement_price'] * 0.05 / 100);
            $response['specs']['options'][$k]['return_back_two_integral'] = sprintf("%.1f",$v['agreement_price'] * 0.05 / 100);
            $response['specs']['options'][$k]['return_back_gold_coin'] = sprintf("%.1f",$v['agreement_price'] * Config::get("gold_coin_config") / 100);

            #删除多余数据
            unset($response['specs']['options'][$k]['third_id']);
            unset($response['specs']['options'][$k]['guide_price']);
            unset($response['specs']['options'][$k]['activity_price']);
            unset($response['specs']['options'][$k]['sale_price']);
            unset($response['specs']['options'][$k]['status']);
            unset($response['specs']['options'][$k]['old_goods_id']);
            unset($response['specs']['options'][$k]['agreement_price']);
        }


        #处理多余数据
        unset($response['agreement_price']);
        unset($response['third_id']);
        unset($response['shop_id']);
        unset($response['category_id']);
        unset($response['brand_id']);
        unset($response['third_category_name']);
        unset($response['unit']);
        unset($response['guide_price']);
        unset($response['sale_price']);
        unset($response['activity_price']);
        unset($response['activity_rate']);
        unset($response['real_sale']);
        unset($response['real_month_sale']);
        unset($response['real_return_sale']);
        unset($response['real_month_return_sale']);
        unset($response['choose_count']);
        unset($response['created_time']);
        unset($response['updated_time']);

        returnJson(200,"success",$response);
    }
    #zlc-返利商品品牌列表
    public function brandList()
    {
        $data = $this->supply->brandList();
        returnJson(200,'success',$data);
    }
    #zlc-爆品商城商品展示
    public function hotShopList()
    {
        $data = input();
        $source = empty($data['source']) ? 0 : $data['source'];
        $type = empty($data['type']) ? 1 : $data['type'];
        if($type == 2)
        {
            $order = ['sale'=>"desc"];
        }else if($type == 3)
        {
            $order = ['agreement_price'=>"asc"];
        }else if($type == 4)
        {
            $order = ['agreement_price'=>"desc"];
        }else{
            $order = ['id'=>"desc"];
        }
        if($source == 0)
        {
            $where = "shop_type = 0 or shop_type = 2";
        }else{
            $where = "(shop_type = 0 or shop_type = 2) and source = '$source'";
        }
        if(!empty($data['cate_id']))
        {
            $cate_id = $data['cate_id'];
            $where = "(".$where .") and FIND_IN_SET($cate_id,cate_id)";
        }
        #品牌
        if(!empty($data['brand_id']))
        {
            $brand = Db::name("choice_brand")
                ->field("brand_name")
                ->where(['id'=>$data['brand_id']])
                ->find();
            $brand_name = $brand['brand_name'];
            $where = "(".$where .") and brand_name = '$brand_name'";
        }
        #活动分类
        if(!empty($data['activity_type']))
        {
            $activity_type = $data['activity_type'];
            $where = "(".$where .") and activity_id = '$activity_type'";
        }
        #价格区间
        if(!empty($data['range_from']))
        {
            $range_from = intval($data['range_from'] * 100 / 1.5);
            $where = "(".$where .") and agreement_price > '$range_from'";
        }
        if(!empty($data['range_to']))
        {
            $range_to = intval($data['range_to'] * 100 / 1.5);
            $where = "(".$where .") and agreement_price < '$range_to'";
        }
        if(!empty($data['sou']))
        {
            $sou = $data['sou'];
            $cate_name = Db::name("choice_cate")
                ->field("id")
                ->where(['name'=>$sou])
                ->find();
            if($cate_name == null)
            {
                $cateId = 0;
            }else{
                $cateId = $cate_name['id'];
            }

            $where = "(".$where .") and title like '%$sou%' or FIND_IN_SET($cateId,cate_id)";
        }


        $current_page = empty($data['current_page']) ? 1 : $data['current_page'];
        $page_num = empty($data['page_num']) ? 10 : $data['page_num'];
        $data = $this->supply->hotShopList($current_page,$page_num,$where,$order);
        returnJson(200,"success",$data);
    }
    #zlc-返利商城首页商品展示
    public function rebateShopList()
    {
        $data = input();
        $source = empty($data['source']) ? 0 : $data['source'];
        $type = empty($data['type']) ? 1 : $data['type'];
        if($type == 2)
        {
            $order = ['sale'=>"desc"];
        }else if($type == 3)
        {
            $order = ['agreement_price'=>"asc"];
        }else if($type == 4)
        {
            $order = ['agreement_price'=>"desc"];
        }else{
            $order = ['id'=>"desc"];
        }
        if($source == 0)
        {
            $where = "shop_type = 0 or shop_type = 1";
        }else{
            $where = "(shop_type = 0 or shop_type = 1) and source = '$source'";
        }
        if(!empty($data['cate_id']))
        {
            $cate_id = $data['cate_id'];
            $where = "(".$where .") and FIND_IN_SET($cate_id,cate_id)";
        }
        #品牌
        if(!empty($data['brand_id']))
        {
            $brand = Db::name("choice_brand")
                ->field("brand_name")
                ->where(['id'=>$data['brand_id']])
                ->find();
            $brand_name = $brand['brand_name'];
            $where = "(".$where .") and brand_name = '$brand_name'";
        }
        #活动分类
        if(!empty($data['activity_type']))
        {
            $activity_type = $data['activity_type'];
            $where = "(".$where .") and activity_id = '$activity_type'";
        }
        #价格区间
        if(!empty($data['range_from']))
        {
            $range_from = intval($data['range_from'] * 100 / 1.5);
            $where = "(".$where .") and agreement_price > '$range_from'";
        }
        if(!empty($data['range_to']))
        {
            $range_to = intval($data['range_to'] * 100 / 1.5);
            $where = "(".$where .") and agreement_price < '$range_to'";
        }
        if(!empty($data['sou']))
        {
            $sou = $data['sou'];
            $cate_name = Db::name("choice_cate")
                ->field("id")
                ->where(['name'=>$sou])
                ->find();
            if($cate_name == null)
            {
                $cateId = 0;
            }else{
                $cateId = $cate_name['id'];
            }

            $where = "(".$where .") and title like '%$sou%' or FIND_IN_SET($cateId,cate_id)";
        }


        $current_page = empty($data['current_page']) ? 1 : $data['current_page'];
        $page_num = empty($data['page_num']) ? 10 : $data['page_num'];
        $data = $this->supply->rebateShopList($current_page,$page_num,$where,$order);
        returnJson(200,"success",$data);
    }
    #商品详情
    public function detail()
    {
        $param = input();
        $validate = new Validate([
            ['id', 'require', '商品ID不能为空'],
        ]);
        if(!$validate->check($param))
        {
            returnJson(-2003,$validate->getError());
        }
        $method = 'GET';//请求方法
        $action = '/v2/Goods/Detail';//请求资源名
        $response = $this->client->getApiResponse($method,$action,$param);
        $response = json_decode($response,true)['data'];
        dump($response);die;

    }
    #供应链商品分类列表展示
    public function cateList()
    {
        $input = input();
        $current_page = empty($input['current_page']) ? 1 : $input['current_page'];
        $page_num = empty($input['page_num']) ? 10: $input['page_num'];
        $parent_id = empty($input['parent_id']) ? 0: $input['parent_id'];
        $data = $this->supply->cateList($current_page,$page_num,$parent_id);
        returnJson(200,"success",$data);

    }
    #商品品牌同步本地数据库
    public function brandName()
    {
        echo "别瞎闹,消息自动同步了!";die;
        $this->supply->brandName();
        returnJson(200,"品牌数据同步成功");
    }
    #选品库商品同步本地数据库
    public function myLists()
    {
        echo "别瞎闹,消息自动同步了!";die;
        $data = input();
        $param['page'] = empty($data['current_page']) ? 1 : $data['current_page'];
        $param['limit'] = empty($data['page_num']) ? 10 : $data['page_num'];
        $param['source'] = $data['source'];
        if(!empty($data['category_id']))
        {
            $param['category_id'] = $data['category_id'];
        }

        $method = 'GET';//请求方法
        $action = '/v2/GoodsStorage/MyLists';//请求资源名
        $response = $this->client->getApiResponse($method,$action,$param);
        $response = json_decode($response,true)['data']['list'];

        #添加到本地数据库
        foreach ($response as $k=>$v)
        {
            $count = Db::name("choice_goods")
                ->where(['goods_id'=>$v['id']])
                ->count();
            if($count)
            {
                #同步数据
                $insert['title'] = $v['title'];
                $insert['goods_id'] = $v['id'];
                $insert['brand_name'] = empty($v['third_brand_name']) ? "其他" : $v['third_brand_name'];
                $insert['source'] = $v['source'];
                $insert['market_price'] = $v['market_price'];
                $insert['agreement_price'] = $v['agreement_price'];
                $insert['cover'] = $v['cover'];
                $insert['stock'] = $v['stock'];
                $insert['total_stock'] = $v['total_stock'];
                $insert['status'] = $v['status'];
                $insert['sale'] = $v['sale'];
                $insert['is_free_shipping'] = $v['is_free_shipping'];
                $insert['update_time'] = time();
                Db::name("choice_goods")
                    ->where(['goods_id'=>$v['id']])
                    ->update($insert);
            }else{
                #新增数据
                $insert['goods_id'] = $v['id'];
                $insert['title'] = $v['title'];
                $insert['brand_name'] = empty($v['third_brand_name']) ? "其他" : $v['third_brand_name'];
                $insert['source'] = $v['source'];
                $insert['market_price'] = $v['market_price'];
                $insert['agreement_price'] = $v['agreement_price'];
                $insert['cover'] = $v['cover'];
                $insert['stock'] = $v['stock'];
                $insert['total_stock'] = $v['total_stock'];
                $insert['status'] = $v['status'];
                $insert['sale'] = $v['sale'];
                $insert['is_free_shipping'] = $v['is_free_shipping'];
                $insert['create_time'] = time();
                Db::name("choice_goods")->insert($insert);
            }
        }
        returnJson(200,"数据同步成功");

    }
    #获取商品列表
    public function goodsLists()
    {
        $data = input();
        $param['page'] = empty($input['current_page']) ? 1 : $input['current_page'];
        $param['limit'] = empty($input['page_num']) ? 10: $input['page_num'];
        $param['source'] = $data['source'];
        $param['category_id'] = $data['category_id'];

        $method = 'GET';//请求方法
        $action = '/v2/Goods/Lists';//请求资源名
        $response = $this->client->getApiResponse($method,$action,$param);
        $response = json_decode($response,true)['data'];
        dump($response);die;

    }

    #获取分类列表
    public function category()
    {
        $param = input();
        $validate = new Validate([
            ['source', 'require', '商品来源不能为空'],
            ['parent_id', 'require', '分类ID不能为空'],
        ]);
        if(!$validate->check($param))
        {
            returnJson(-2003,$validate->getError());
        }
        $method = 'GET';//请求方法
        $action = '/v2/Category/GetCategory';//请求资源名
        $response = $this->client->getApiResponse($method,$action,$param);
        $response = json_decode($response,true)['data'];
        foreach ($response as $k=>$v)
        {
            if($v['state'] == 0)
            {
                unset($response[$k]);
            }
            unset($response[$k]['real_id']);
            unset($response[$k]['state']);
            unset($response[$k]['sort']);
        }
        returnJson(200,"success",$response);


    }
    public function test()
    {
        //获取商品列表
        $param = input();
        $method = 'GET';//请求方法
        $action = '/v2/Category/Lists';//请求资源名
        $response = $this->client->getApiResponse($method,$action,$param);
        $response = json_decode($response,true)['data'];
        dump($response);die;
        returnJson(200,"success",$response['list']);

    }

}